package com.api.volunteer.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/3/30 15:00
 */
public class JWTUtil {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String SECRET = "njnkaaa";
    public static final String ISS = "1003219977";

    //过期时间6小时
    private static final Long EXPIRATION = 12 * 60 * 60L;

    //创建token
    public static String createToken(String openid, String secretKey){
        Map map = new HashMap();
        map.put("openid", openid);
        map.put("secretKey", secretKey);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
    }

    public static Claims getTokenBody(String token){
        Claims claims = null;
        try{
            claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        } catch(Exception e){
            e.printStackTrace();
        }
        return claims;
    }

    //是否已过期
    public static boolean isExpiration(String token){
        try{
            return getTokenBody(token).getExpiration().before(new Date());
        } catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }
}
